import {
  bindPhone,
  userInfo,
  editUserInfo,
  orderDetails
} from '../../apis/user';
import {
  signUp
} from '../../apis/activity';
const app = getApp();

Page({
  data: {
    form: {
      credentials: '身份证',
      unitId: -1
    },
    pickerShow: false,
    cardIndex: [0],
    cardType: ['身份证', '港澳通行证', '护照']
  },

  onLoad(options) {
    this.setData({
      ...options
    });
    if (options.type === 'activity') {
      wx.setNavigationBarTitle({
        title: '活动报名'
      });
    };
    this.getUserInfo();
  },

  // 获取个人信息
  getUserInfo() {
    wx.showLoading({
      title: '加载中...'
    });
    userInfo().then(res => {
      wx.hideLoading();
      if (res.data.code === 200) {
        let {
          user
        } = res.data.data;
        if (user) {
          user.avatar = user.avatar ? user.avatar : app.globalData.userInfo.avatarUrl;
          user.unitId = user.unitId ? user.unitId : -1;
          user.username = user.username ? user.username : app.globalData.userInfo.nickName;
          user.gender = user.gender ? user.gender : app.globalData.userInfo.gender;
          let index = this.data.cardType.findIndex(v => v === user.credentials) === -1 ? 0 : this.data.cardType.findIndex(v => v === user.credentials);
          this.setData({
            form: user,
            cardIndex: [index]
          });
        } else if (!user && app.globalData.isAuthorization) {
          user.username = app.globalData.userInfo.nickName;
          user.gender = app.globalData.userInfo.gender;
          user.avatar = app.globalData.userInfo.avatarUrl;
          this.setData({
            form: user
          });
        };
      };
    });
  },
  getOrderDetails(orderNo) {
    orderDetails(orderNo).then(res => {
      if (res.data.code === 200) {
        let {
          orderDetail
        } = res.data.data;
        let index = this.data.cardType.findIndex(v => v === orderDetail.credentials);
        if (orderDetail.unitId == -1) {
          orderDetail.unitExtra = orderDetail.unit;
        };
        this.setData({
          form: orderDetail,
          cardIndex: [index]
        });
      };
    });
  },

  // 获取个人信息
  bindgetuserinfo(e) {
    if (e.detail.userInfo) {
      app.globalData.isAuthorization = true;
      app.globalData.userInfo = e.detail.userInfo;
      let {
        nickName,
        gender,
        avatarUrl
      } = e.detail.userInfo;
      this.setData({
        'form.username': nickName,
        'form.gender': gender,
        'form.avatar': avatarUrl
      });
    };
  },

  // 获取手机号
  bindgetphonenumber(e) {
    if (e.detail.encryptedData) {
      bindPhone(e.detail.encryptedData, e.detail.iv).then(res => {
        if (res.data.code === 200) {
          let {
            data
          } = res.data;
          this.setData({
            'form.phone': data
          });
        };
      });
    };
  },

  // 解密手机号
  decryptPhone(encryptedData, iv) {
    decryptPhone(encryptedData, iv).then(res => {
      if (res.data.code === 200) {
        let {
          phone
        } = res.data.data.user;
        this.setData({
          'form.phone': phone
        });
      };
    });
  },

  // 选择证件
  showPicker() {
    this.setData({
      pickerShow: true
    });
  },
  confirmPicker(e) {
    let {
      cardIndex
    } = e.detail;
    this.setData({
      cardIndex: cardIndex,
      'form.credentials': this.data.cardType[cardIndex[0]],
      pickerShow: false
    });
  },

  // 选择单位
  selectUnit() {
    wx.navigateTo({
      url: '/pages/affiliatedUnit/index'
    });
  },

  // 表单提交
  formSubmit(e) {
    let {
      value
    } = e.detail;

    value.avatar = this.data.form.avatar ? this.data.form.avatar : '';

    if (!value.username) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return
    };

    if (!value.gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return
    };

    if (!value.phone && this.data.type === 'activity') {
      wx.showToast({
        title: '请获取手机号',
        icon: 'none'
      });
      return
    };

    value.credentials = this.data.cardType[this.data.cardIndex[0]];

    if (!value.idNo) {
      wx.showToast({
        title: '请输入证件号码',
        icon: 'none'
      });
      return
    } else if (value.credentials == '身份证' && value.idNo.length !== 18) {
      wx.showToast({
        title: '请正确输入身份证号码',
        icon: 'none'
      });
      return
    };

    if (this.data.form.unitId == -1) {
      if (!value.unitExtra) {
        wx.showToast({
          title: '请输入单位名称',
          icon: 'none'
        });
        return
      };
      value.unitId = -1;
    } else {
      value.unitId = this.data.form.unitId;
      delete value.unitExtra
    };

    // if (!value.email) {
    //   wx.showToast({
    //     title: '请输入邮箱',
    //     icon: 'none'
    //   });
    //   return
    // } else if (!new RegExp('^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$').test(value.email)) {
    //   wx.showToast({
    //     title: '邮箱格式错误',
    //     icon: 'none'
    //   });
    //   return
    // };
    if (!value.post) {
      wx.showToast({
        title: '请输入邮箱',
        icon: 'none'
      });
      return
    } 

    if (this.data.type === 'activity') {
      wx.requestSubscribeMessage({
        tmplIds: ['JsprYJQo0_5sqvNzHjrPlHrIZdn0hsEoy-kp6NUaDgs', '_quuyfAlYNQwnbSdnyvgXveDHPNZ99V3h072l0jRhHs', 'pE5LxEcdYHS6B-TiE45j-GjiX-aV9e-KrHagJ1h4bbQ'],
        complete: res => {
          this.editUserInfo(value);
        }
      });
    } else {
      this.editUserInfo(value);
    };
  },

  // 修改信息
  editUserInfo(form) {
    if (this.data.type === 'activity') {
      wx.showLoading({
        title: '提交中...',
        mask: true
      });
    } else {
      wx.showLoading({
        title: '修改中...',
        mask: true
      });
    };
    editUserInfo(form).then(res => {
      if (this.data.type !== 'activity') {
        wx.hideLoading();
      };
      if (res.data.code === 200) {
        if (this.data.type !== 'activity') {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            mask: true,
            duration: 1500,
            success: res => {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                });
              }, 1500);
            }
          });
        } else {
          this.submitSignUp(form);
        };
      };
    });
  },

  // 提交报名
  submitSignUp(form) {
    signUp(this.data.activityId, form).then(res => {
      wx.hideLoading();
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        wx.showModal({
          content: '已成功提交报名信息，平台管理员将在1-3个工作日进行信息审核',
          confirmText: '知道了',
          showCancel: false,
          success: res => {
            wx.redirectTo({
              url: `/pages/orderDetails/index?orderNo=${data}`
            });
            // let pages = getCurrentPages();
            // let prevPage = pages[pages.length - 2];
            // prevPage.setData({
            //   'activityDetails.hasEnroll': true
            // });
            // wx.navigateBack({
            //   delta: 1
            // });
          }
        });
      };
    });
  }
})